package dao;

import java.io.FileWriter;
import java.util.*;

import org.dom4j.*;
import org.dom4j.io.*;

import po.Shop;
import util.PathTool;

public class ShopDao {
	private static String tableName;
	private static String xmlPathr;
	private static Document document;
	
	static {
		tableName = "shop";
		xmlPathr = PathTool.getWebPath() + "xmlData/" + tableName + ".xml";
		try {
			SAXReader sr = new SAXReader();
	        document = sr.read(xmlPathr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static boolean addOneRecord(Shop s) { // 添加一条记录
		Element root = document.getRootElement();
		Element newE = root.addElement(tableName);
		// 添加主键
		newE.addAttribute("productId", s.getProductId());
		newE.addAttribute("sellerId", s.getSellerId());
		newE.addAttribute("buyerId", s.getBuyerId());
		// 添加属性
		newE.addElement("amount").setText(String.valueOf(s.getAmount()));
		newE.addElement("status").setText(String.valueOf(s.getStatus()));
		
		writeToNewXMLDocument();
		return true;
	}
	
	public static boolean queryOneRecord(Shop s) { // 根据 主码 查询一条数据
		Element root = document.getRootElement();
		List<Element> userList =  root.elements(); // 所有记录组成的集合
		// 开始查找对应的 id
		Element temp;
		for (int i=0; i<userList.size(); i++) {
			temp = userList.get(i); // 一条记录
			// 判断 主码
			if (checkRecordPrimaryKey(s, temp)) {
				List<Element> userElementList = temp.elements();
				// 开始补齐数据
				for (int j=0; j<userElementList.size(); j++) {
					Element te = userElementList.get(j);
					if ("amount".equals(te.getName())) {
						s.setAmount(Integer.parseInt(te.getText()));
					} else if ("status".equals(te.getName())) {
						s.setStatus(Integer.parseInt(te.getText()));
					}
				}
				return true;
			}
		}
		return false; // 没找到
	}
	
	public static boolean updataOneRecord(Shop s) { // 更新一条记录 
		Element root = document.getRootElement();
		List<Element> users = root.elements();
		Element temp;
		
		for (int i=0; i<users.size(); i++) {
			temp = users.get(i);
			if (checkRecordPrimaryKey(s, temp)) {
				for (Iterator<Element> it = temp.elementIterator(); it.hasNext();) { // 通过迭代器 遍历
                    Element node = it.next();
                    String type = node.getName();
                    if ("amount".equals(type)) {
                        node.setText(String.valueOf(s.getAmount()));
                    } else if ("status".equals(type)) {
                    	node.setText(String.valueOf(s.getStatus()));
                    }
                }
			}
		}
		writeToNewXMLDocument();
		return true;
	}
	
	private static boolean checkRecordPrimaryKey (Shop s, Element temp) {
		if (temp.attributeValue("productId").equals(s.getProductId()) 
				&& temp.attributeValue("sellerId").equals(s.getSellerId())
				&& temp.attributeValue("buyerId").equals(s.getBuyerId()))
			return true;
		return false;
	}
	
	public static Shop[] queryAllRecord() { // 查询所有
		Element root = document.getRootElement();
		List<Element> list = root.elements();
		Element temp;
		int amount = list.size();
		Shop[] s = new Shop[amount]; // 数组
		Shop tempStore;
		for (int i=0; i<amount; i++) {
			temp = list.get(i);
			tempStore = new Shop();
			// 设置主码
			tempStore.setSellerId(temp.attributeValue("sellerId"));
			tempStore.setProductId(temp.attributeValue("productId"));
			tempStore.setBuyerId(temp.attributeValue("buyerId"));
			
			for (Iterator<Element> it = temp.elementIterator(); it.hasNext();) {
                Element node =  it.next();
                String type = node.getName();
                if ("amount".equals(type)) {
                	tempStore.setAmount(Integer.valueOf(node.getText()));
                } else if ("status".equals(type)) {
                	tempStore.setStatus(Integer.valueOf(node.getText()));
                }
            }
			s[i] = tempStore;
		}
		return s;
	}
	
    private static void writeToNewXMLDocument() {
    	try {
            XMLWriter writer = new XMLWriter(new FileWriter(
            		xmlPathr));
            writer.write(document);
            writer.close();
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    }
	
}
